﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Modles.DTO;
using Modles.Models;

namespace BilbilDAL
{
    public class VideoInfoDAL
    {
        /// <summary>
        /// 获取主页视频信息（时间降序排序，提供分页功能）
        /// </summary>
        /// <param name="model"></param>
        /// <param name="TotalCount"></param>
        /// <returns></returns>
        public List<VideoInfo_DTO> GetVideoInfo(int page, int limit, out int TotalCount)
        {
            using (VideoPlatformDbContext con = new VideoPlatformDbContext())
            {
                IQueryable<VideoInfo_DTO> iquery = from a in con.VideoInfos
                                                   join b in con.Videos on a.VideoId equals b.Id
                                                   join c in con.Images on a.ImageId equals c.Id
                                                   join d in con.VideoTypes on a.VideoTypeId equals d.Id
                                                   join e in con.UserInfos on a.UserInfoId equals e.Id
                                                   select new VideoInfo_DTO
                                                   {
                                                       Id = a.Id,
                                                       VideoId = a.VideoId,
                                                       ImageId = a.ImageId,
                                                       VideoTypeId = a.VideoTypeId,
                                                       UserInfoId = a.UserInfoId,
                                                       Title = a.Title,
                                                       Briefintroduction = a.Briefintroduction,
                                                       Label = a.Label,
                                                       Time = a.Time,
                                                       Like = a.Like,
                                                       Views = a.Views,
                                                       VideoAddress = b.Address,
                                                       ImageAddress = c.Address,
                                                       VideoType = d.Type,
                                                       UserName = e.Name,
                                                       UserAvatar = e.Avatar
                                                   };
                TotalCount = iquery.Count();
                List<VideoInfo_DTO> list = iquery
                    .OrderByDescending(x => x.Time)
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                return list;
            }
        }
        /// <summary>
        /// 打印视频信息表，按播量排序，仅输出前100个视频信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="TotalCount"></param>
        /// <returns></returns>
        public List<VideoInfo_DTO> GetVideoInfoSort()
        {
            using (VideoPlatformDbContext con = new VideoPlatformDbContext())
            {
                IQueryable<VideoInfo_DTO> iquery = from a in con.VideoInfos
                                                   join b in con.Videos on a.VideoId equals b.Id
                                                   join c in con.Images on a.ImageId equals c.Id
                                                   join d in con.VideoTypes on a.VideoTypeId equals d.Id
                                                   join e in con.UserInfos on a.UserInfoId equals e.Id
                                                   select new VideoInfo_DTO
                                                   {
                                                       Id = a.Id,
                                                       VideoId = a.VideoId,
                                                       ImageId = a.ImageId,
                                                       VideoTypeId = a.VideoTypeId,
                                                       UserInfoId = a.UserInfoId,
                                                       Title = a.Title,
                                                       Briefintroduction = a.Briefintroduction,
                                                       Label = a.Label,
                                                       Time = a.Time,
                                                       Like = a.Like,
                                                       Views = a.Views,
                                                       VideoAddress = b.Address,
                                                       ImageAddress = c.Address,
                                                       VideoType = d.Type,
                                                       UserName = e.Name,
                                                       UserAvatar = e.Avatar
                                                   };
                List<VideoInfo_DTO> list =
                    iquery.
                    OrderByDescending(x => x.Views)
                    .Take(100)
                    .ToList();
                return list;
            }
        }
        /// <summary>
        /// 根据视频信息表的视频标题模糊查询，打印查询到的视频信息表按视频发布时间降序排序，提供分页功能
        /// </summary>
        /// <param name="model"></param>
        /// <param name="TotalCount"></param>
        /// <returns></returns>
        public List<VideoInfo_DTO> GetVideoInfoBytitle(StudentQuery_DTO model, out int TotalCount)
        {
            using (VideoPlatformDbContext con = new VideoPlatformDbContext())
            {
                IQueryable<VideoInfo_DTO> iquery = from a in con.VideoInfos
                                                   join b in con.Videos on a.VideoId equals b.Id
                                                   join c in con.Images on a.ImageId equals c.Id
                                                   join d in con.VideoTypes on a.VideoTypeId equals d.Id
                                                   join e in con.UserInfos on a.UserInfoId equals e.Id
                                                   select new VideoInfo_DTO
                                                   {
                                                       Id = a.Id,
                                                       VideoId = a.VideoId,
                                                       ImageId = a.ImageId,
                                                       VideoTypeId = a.VideoTypeId,
                                                       UserInfoId = a.UserInfoId,
                                                       Title = a.Title,
                                                       Briefintroduction = a.Briefintroduction,
                                                       Label = a.Label,
                                                       Time = a.Time,
                                                       Like = a.Like,
                                                       Views = a.Views,
                                                       VideoAddress = b.Address,
                                                       ImageAddress = c.Address,
                                                       VideoType = d.Type,
                                                       UserName = e.Name,
                                                       UserAvatar = e.Avatar
                                                   };
                if (!string.IsNullOrEmpty(model.title))
                {
                    iquery = iquery.Where(x => x.Title.Contains(model.title));
                }
                TotalCount = iquery.Count();
                List<VideoInfo_DTO> list =
                    iquery.
                    OrderByDescending(x => x.Time)
                    .Skip((model.page - 1) * model.limit)
                    .Take(model.limit)
                    .ToList();
                return list;
            }
        }
        /// <summary>
        /// 通过前端传过来的用户信息表id，视频信息表id和评论内容给视频评论表添加数据
        /// </summary>
        /// <param name="userInfoId">用户信息表ID</param>
        /// <param name="videoInfoId">视频信息表ID</param>
        /// <param name="content">评论内容</param>
        /// <returns>操作结果：成功返回true，失败返回false</returns>
        public bool AddVideoComment(int userInfoId, int videoInfoId, string content)
        {
            try
            {
                // 参数验证
                if (userInfoId <= 0 || videoInfoId <= 0 || string.IsNullOrEmpty(content))
                {
                    return false;
                }
                // 评论内容长度验证
                if (content.Length > 500)
                {
                    return false;
                }
                using (VideoPlatformDbContext con = new VideoPlatformDbContext())
                {
                    // 验证用户是否存在
                    bool userExists = con.UserInfos.Any(u => u.Id == userInfoId);
                    if (!userExists)
                    {
                        return false;
                    }
                    // 验证视频是否存在
                    bool videoExists = con.VideoInfos.Any(v => v.Id == videoInfoId);
                    if (!videoExists)
                    {
                        return false;
                    }
                    // 创建评论对象
                    Comment comment = new Comment
                    {
                        UserInfoId = userInfoId,
                        VideoInfoId = videoInfoId,
                        Content = content.Trim(),
                        Time = DateTime.Now
                    };
                    // 添加评论到数据库
                    con.Comments.Add(comment);
                    int result = con.SaveChanges();
                    // 返回操作结果
                    return result > 0;
                }
            }
            catch
            {
                // 发生异常时返回false
                return false;
            }
        }
        /// <summary>
        /// 根据视频ID获取评论数据
        /// </summary>
        /// <param name="videoInfoId">视频信息表ID</param>
        /// <returns>评论数据列表</returns>
        public Response_DTO<List<CommentInfo_DTO>> GetCommentsByVideoId(int videoInfoId)
        {
            try
            {
                // 参数验证
                if (videoInfoId <= 0)
                {
                    return new Response_DTO<List<CommentInfo_DTO>>
                    {
                        Success = false,
                        Message = "视频信息ID无效"
                    };
                }

                using (var context = new VideoPlatformDbContext())
                {
                    // 验证视频是否存在
                    if (!context.VideoInfos.Any(v => v.Id == videoInfoId))
                    {
                        return new Response_DTO<List<CommentInfo_DTO>>
                        {
                            Success = false,
                            Message = "指定的视频不存在"
                        };
                    }

                    // 查询评论数据
                    var comments = (from comment in context.Comments
                                    join user in context.UserInfos on comment.UserInfoId equals user.Id
                                    orderby comment.Time descending
                                    select new CommentInfo_DTO
                                    {
                                        Id = comment.Id,
                                        Content = comment.Content,
                                        CreateTime = comment.Time,
                                        UserInfoId = comment.UserInfoId,
                                        UserName = user.Name,
                                        UserAvatar = user.Avatar,
                                    }).ToList();

                    return new Response_DTO<List<CommentInfo_DTO>>
                    {
                        Success = true,
                        Message = "获取评论数据成功",
                        Conten = comments
                    };
                }
            }
            catch (Exception ex)
            {
                // 异常处理
                return new Response_DTO<List<CommentInfo_DTO>>
                {
                    Success = false,
                    Message = "获取评论数据时发生错误: " + ex.Message
                };
            }
        }
        /// <summary>
        /// 获取用户发布视频的数量
        /// </summary>
        /// <param name="UserInfoId"></param>
        /// <returns></returns>
        public int GetUserVideoCount(int UserInfoId)
        {
            using (VideoPlatformDbContext con = new VideoPlatformDbContext())
            {
                return con.VideoInfos.Where(x => x.UserInfoId == UserInfoId).Count();
            }
        }
        /// <summary>
        /// 获取用户发布的所有视频
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <returns></returns>
        public List<VideoInfo_DTO> GetUserPublishVideoInfo(int userInfoId)
        {
            using (VideoPlatformDbContext con = new VideoPlatformDbContext())
            {
                IQueryable<VideoInfo_DTO> iquery = from a in con.VideoInfos
                                                   join b in con.Videos on a.VideoId equals b.Id
                                                   join c in con.Images on a.ImageId equals c.Id
                                                   join d in con.VideoTypes on a.VideoTypeId equals d.Id
                                                   join e in con.UserInfos on a.UserInfoId equals e.Id
                                                   select new VideoInfo_DTO
                                                   {
                                                       Id = a.Id,
                                                       VideoId = a.VideoId,
                                                       ImageId = a.ImageId,
                                                       VideoTypeId = a.VideoTypeId,
                                                       UserInfoId = a.UserInfoId,
                                                       Title = a.Title,
                                                       Briefintroduction = a.Briefintroduction,
                                                       Label = a.Label,
                                                       Time = a.Time,
                                                       Like = a.Like,
                                                       Views = a.Views,
                                                       VideoAddress = b.Address,
                                                       ImageAddress = c.Address,
                                                       VideoType = d.Type,
                                                       UserName = e.Name,
                                                       UserAvatar = e.Avatar
                                                   };
                iquery = iquery.Where(x => x.UserInfoId == userInfoId);
                return iquery.ToList();
            }
        }
        /// <summary>
        /// 删除用户发布的指定视频
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <param name="videoInfoId"></param>
        /// <returns></returns>
        public bool DeleteUserPublishVideoInfo(int userInfoId, int videoInfoId)
        {
            using (VideoPlatformDbContext con = new VideoPlatformDbContext())
            {
                VideoInfo videoInfo = con.VideoInfos.FirstOrDefault(x => x.UserInfoId == userInfoId && x.Id == videoInfoId);
                if (videoInfo == null)
                {
                    return false;
                }
                con.Remove(videoInfo);
                return con.SaveChanges() > 0;
            }
        }
        /// <summary>
        /// 根据视频id获取视频信息
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <param name="videoInfoId"></param>
        /// <returns></returns>
        public VideoInfo_DTO GetVideoInfoById(int userInfoId, int videoInfoId)
        {
            using (VideoPlatformDbContext con = new VideoPlatformDbContext())
            {
                IQueryable<VideoInfo_DTO> iquery = from a in con.VideoInfos
                                                   join b in con.Videos on a.VideoId equals b.Id
                                                   join c in con.Images on a.ImageId equals c.Id
                                                   join d in con.VideoTypes on a.VideoTypeId equals d.Id
                                                   join e in con.UserInfos on a.UserInfoId equals e.Id
                                                   select new VideoInfo_DTO
                                                   {
                                                       Id = a.Id,
                                                       VideoId = a.VideoId,
                                                       ImageId = a.ImageId,
                                                       VideoTypeId = a.VideoTypeId,
                                                       UserInfoId = a.UserInfoId,
                                                       Title = a.Title,
                                                       Briefintroduction = a.Briefintroduction,
                                                       Label = a.Label,
                                                       Time = a.Time,
                                                       Like = a.Like,
                                                       Views = a.Views,
                                                       VideoAddress = b.Address,
                                                       ImageAddress = c.Address,
                                                       VideoType = d.Type,
                                                       UserName = e.Name,
                                                       UserAvatar = e.Avatar
                                                   };
                VideoInfo_DTO videoInfo_DTO = iquery.FirstOrDefault(x => x.Id == videoInfoId);
                if(videoInfo_DTO == null) { return null; }
                //判断视频观看记录是否存在
                VideoHistory videoHistory = con.VideoHistories.FirstOrDefault(x => x.UserInfoId == userInfoId && x.VideoInfoId == videoInfoId);
                if (videoHistory == null)
                {
                    //如果不存在，添加视频历史记录
                    con.Add(new VideoHistory() { UserInfoId = userInfoId, VideoInfoId = videoInfoId, DateTime = DateTime.Now });
                } else
                {
                    //如果存在，修改视频历史记录
                    videoHistory.DateTime = DateTime.Now;
                    con.Update(videoHistory);
                    //视频播放量加一
                    videoInfo_DTO.Views += 1;
                    con.Update(videoInfo_DTO);
                }

                if (con.SaveChanges() > 0)
                {
                    return videoInfo_DTO;
                }
                return null;
            }
        }
    }
}


